import { closeSync, open, openSync, write, writeSync } from 'fs';
import * as vscode from 'vscode';

class BeeformPanel {
	private static instance: vscode.WebviewPanel;
	private static isDisposed: boolean = true;
	private constructor() {

	}
	public static getInstance() {
		if (!BeeformPanel.instance ||  BeeformPanel.isDisposed) {
			BeeformPanel.instance = vscode.window.createWebviewPanel(
				"beefirm",
				"beefirm panel",
				vscode.ViewColumn.Two
			);
			BeeformPanel.isDisposed = false
		}
		BeeformPanel.instance.onDidDispose(()=>{
			BeeformPanel.isDisposed = true
		})
		
		return BeeformPanel.instance;
	}
}


export function activate(context: vscode.ExtensionContext) {


	console.log('毕方插件已激活!');

	const child_process = require('child_process');

	let disposable = vscode.commands.registerCommand('beefirm.showUML', () => {


		try {
			let fd = openSync("/tmp/tmp.beefirm", 'w', 0o666)

			let content = vscode.window.activeTextEditor?.document.getText()


			if (content != "" && content != undefined) {
				writeSync(fd, content)
			}
			closeSync(fd)

			const beefirm_shell = child_process.exec(`beefirm /tmp/tmp.beefirm -url`,
				function (err: String, stdout: String, stderr: String) {
					console.log(stdout)
					console.error(stderr)


					if (err && err != "") {
						console.error(stderr)
						vscode.window.showErrorMessage(`Error: ${stderr}`);
						const panel = BeeformPanel.getInstance()
						panel.webview.html = getErrorWebviewContent(stderr)
					} else {
						console.log(stdout)
						vscode.window.showInformationMessage(`success: ${stdout}`);
						const panel = BeeformPanel.getInstance()
						panel.webview.html = getWebviewContent(stdout)
						panel.active
					}
				});
		

		} catch (err) {
			console.log(err)
			vscode.window.showErrorMessage(`${err}`);
		}
 

	});

	context.subscriptions.push(disposable);
}

function getWebviewContent(imgUrl: String) {
	return `<!DOCTYPE html>
  <html lang="en">
  <head>
	  <meta charset="UTF-8">
	  <meta name="viewport" content="width=device-width, initial-scale=1.0">
	  <title>Cat Coding</title>
  </head>
  <body>
	  <img id="panel" src="${imgUrl}" />
  </body>
  </html>`;
}
function getErrorWebviewContent(errMsg: String) {
	return `<!DOCTYPE html>
  <html lang="en">
  <head>
	  <meta charset="UTF-8">
	  <meta name="viewport" content="width=device-width, initial-scale=1.0">
	  <title>Cat Coding</title>
  </head>
  <body>
	  ${errMsg}
  </body>
  </html>`;
}

// this method is called when your extension is deactivated
export function deactivate() { }
